package com.StarStudio.RabbitMQ;


import com.StarStudio.Service.PanicBuyingCouponsService;
import com.StarStudio.Service.PanicBuyingGoodsService;
import com.StarStudio.Service.PanicBuyingOrdersService;
import com.ruoyi.common.core.Entity.Orders;
import com.ruoyi.common.core.Entity.PanicBuyingCoupons;
import com.ruoyi.common.core.Entity.PanicBuyingGoods;
import com.ruoyi.common.core.Entity.PanicBuyingOrders;
import com.ruoyi.common.core.utils.JsonUtil;
import com.ruoyi.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * MQ消息接收类  在该类中进行异步下单
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    PanicBuyingGoodsService panicBuyingGoodsService;

    @Autowired
    PanicBuyingCouponsService panicBuyingCouponsService;

    @Autowired
    RedisService redisService;

    @Autowired
    PanicBuyingOrdersService panicBuyingOrdersService;

    @RabbitListener(queues = "PanicBuyingQueue")
    public void receive(String message){
        log.info("接收的消息:" + message);
        Orders orders = JsonUtil.jsonStr2Object(message, Orders.class);
        if (orders != null){
            if (orders.getGoods_id() > 0 && orders.getCoupons_id() ==0){ /* 抢购实体商品 */
                PanicBuyingGoods byGoods_id = panicBuyingGoodsService.findByGoods_id(orders.getGoods_id());
                if (byGoods_id.getPanic_buying_goods_stock() < 1){
                    return;
                }
                //判断是否重复抢购
                PanicBuyingOrders panicBuyingOrders =  redisService.getCacheObject("panic_buying_goods_order:" + orders.getOrder_user_id() + ":" + orders.getGoods_id());
                if (panicBuyingOrders != null){
                    return;
                }
            } else if (orders.getGoods_id() == 0 && orders.getCoupons_id() > 0) { /* 抢购优惠券 */
                PanicBuyingCoupons byCoupons_id = panicBuyingCouponsService.findByCoupons_id(orders.getCoupons_id());
                if (byCoupons_id.getPanic_buying_coupons_stock() < 1){
                    return;
                }
                //判断是否重复抢购
                PanicBuyingOrders panicBuyingOrders =  redisService.getCacheObject("panic_buying_coupons_order:" + orders.getOrder_user_id() + ":" + orders.getCoupons_id());
                if (panicBuyingOrders != null){
                    return;
                }
            }else {
                throw new RuntimeException("参数错误！");
            }
            //下单
            panicBuyingOrdersService.NewPanicBuyingOrders(orders);
        }
    }
}
